<template>
  <el-form ref="formObj" :model="user" :rules="rules" class="wrapper">
    <!-- 头像上传区域 -->
    <h2>头像</h2>
    <el-form-item prop="file">
      <div style="width:100px;height:100px;overflow: hidden;">
        <el-upload
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-change="uploadfile"
            :on-remove="removefile"
            v-model:file-list="filelist">
          <el-icon>
            <defaultuser/>
          </el-icon>
        </el-upload>
      </div>
    </el-form-item>

    <!-- 个人资料区域 -->
    <h2>个人资料</h2>
    <el-row :gutter="10">
      <el-col :span="6">
        <el-form-item label="用户名:" prop="username">
          <el-input maxlength="20" v-model="user.username" placeholder="请输入用户姓名"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6" :offset="3">
        <el-form-item style="margin-left:10px" label="年&nbsp;&nbsp;&nbsp;&nbsp;龄:" prop="age">
          <el-input maxlength="3" v-model="user.age" placeholder="请输入年龄"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item style="margin-left:10px" label="昵&nbsp;&nbsp;&nbsp;&nbsp;称:" prop="nickname">
          <el-input maxlength="20" v-model="user.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="性&nbsp;&nbsp;&nbsp;&nbsp;别:" prop="gender">
          <el-radio-group v-model="user.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 联系方式区域（保留手机号和邮箱） -->
    <h2>联系方式</h2>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="手机号:" prop="phone">
          <el-input maxlength="15" v-model="user.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6" :offset="3">
        <el-form-item label="邮&nbsp;&nbsp;&nbsp;&nbsp;箱:" prop="email">
          <el-input v-model="user.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 保存按钮 -->
    <el-form-item>
      <el-button type="warning" size="default" :icon="Save" @click="save" style="margin-top: 15px;">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import defaultuser from '@/components/icons/defaultuser';
import Save from '@/components/icons/save.vue';
import { ref, reactive } from 'vue';
import { get, post } from '@/plugins/axios'
import { getCookieForObject, setCookiesFromObject } from '@/util';
import { ElMessage } from 'element-plus';
import { userLoadingStore } from '@/stores';

const formObj = ref()
const filelist = ref([])

// 用户信息对象（包含所有保留字段）
const user = reactive({
  id: '',
  username: '',
  nickname: '',
  age: 0,
  gender: null,
  phone: '',
  email: '',
  file: null
})

// 初始化用户信息（从cookie获取）
init()
function init() {
  const userinfo = getCookieForObject('user')
  if (userinfo) {
    for (const key in user) {
      if (Object.prototype.hasOwnProperty.call(userinfo, key)) {
        user[key] = userinfo[key];
      }
    }
  }
}

// 通过token获取最新用户信息
function getByToken() {
  post("/tUser/getByToken", { token: VueCookie.get('token') }, content => {
    for (const key in user) {
      if (Object.prototype.hasOwnProperty.call(content, key)) {
        user[key] = content[key]
      }
    }
    setCookiesFromObject('user', user)
    userLoadingStore().setLoading(true)
    location.reload()
    userLoadingStore().setLoading(false)
  })
}

// 表单验证规则（保留所有字段验证）
const rules = {
  username: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { max: 20, message: '长度在 1 到 20个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '手机号格式错误', trigger: 'blur' },
    { validator: check, message: '该手机号已经被使用', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    { validator: check, message: '该邮箱已经被使用', trigger: 'blur' }
  ]
}

// 验证字段唯一性
function check(rule, value, callback) {
  get("/tUser/check", { id: user.id, value, field: rule.field }, res => {
    if (res) {
      callback();
    } else {
      callback(new Error(''));
    }
  })
}

// 保存修改
function save() {
  formObj.value.validate((valid) => {
    if (valid) {
      post("/tUser/update", user, content => {
        ElMessage.success('修改成功')
        getByToken()
      });
    } else {
      return false;
    }
  });
}

// 处理头像上传
function uploadfile(file) {
  user.file = file.raw
}

// 移除头像
function removefile() {
  user.file = null
}
</script>

<style lang="scss" scoped>
h2 {
  margin-top: 15px;
  border-bottom: 2px solid #f6ab52;
  margin-bottom: 10px;
}
.wrapper {
  max-height: 576px;
  border-radius: 8px;
  background-color: #fff9ef;
  padding: 5px 80px;
}
$imgsize: 100px;
::v-deep .el-upload--picture-card {
  width: $imgsize;
  height: $imgsize;
}
::v-deep .el-upload {
  width: $imgsize;
  height: $imgsize;
  line-height: $imgsize;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: $imgsize;
  height: $imgsize;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: $imgsize;
  height: $imgsize;
  line-height: $imgsize;
}
::v-deep .avatar {
  width: $imgsize;
  height: $imgsize;
}
</style>